/**
 * 根据 Document ready 状态执行不同的函数
 * 加载规则：
 * 1. Document ready is loading | uninitialized -> no call -> Listen on ready state change -> call onInteractive -> call onComplete.
 * 2. Document ready is interactive -> call onInteractive -> Listen on ready state change -> call onComplete.
 * 3. Document ready is complete -> call onInteractive & onComplete.
 * @param {Function} onInteractive 当 Document ready 状态为 interactive 时执行的回调函数
 * @param {Function} onComplete 当 Document ready 状态为 complete 时执行的回调函数
 */
export default function ready(onInteractive, onComplete) {
  console.log("Current document ready state is", document.readyState);

  switch (document.readyState) {
    case "interactive":
      onInteractive();
      break;
    case "complete":
      onInteractive();
      onComplete();
      break;
  }

  if (document.readyState !== "complete") {
    document.addEventListener(
      "readystatechange",
      readystatechangeEventListener
    );
  }

  function readystatechangeEventListener() {
    console.log(
      "Document ready state changed, new state is",
      document.readyState
    );

    switch (document.readyState) {
      case "interactive":
        onInteractive();
        break;
      case "complete":
        onComplete();
        break;
    }
  }
}

/**
 * 动态加载第三方脚本
 * @param {string} url
 * @param {Function} callback
 */
export function loadJs(url, callback) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  if (typeof callback != "undefined") {
    if (script.readyState) {
      script.onreadystatechange = function() {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = callback;
    }
  }
  script.src = url;
  document.body.appendChild(script);
}
